/*    
 * 五星电器公司拥有完全的版权   
 * 使用者必须经过许可
 *----------------------------------------------------------------------*
 * Copyright  (c) 2016 FiveStar Co.,Ltd. All rights reserved
 * Author       : FiveStar Development
 * Description  : FsOAuth2ExceptionnSerializer.java
 *----------------------------------------------------------------------*
 * Change-History: Change history
 * Developer  Date      Description
 * shidong  2017年5月31日 Short description containing Message, Note ID or CR ID
 *----------------------------------------------------------------------*  
 */
package com.twp.auth.utils;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import com.twp.auth.constants.ResultCodeConstants;
import com.twp.auth.myexecption.MyBadCredentialsException;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;

import java.io.IOException;


/**
 * 重新生成oauth2 error的jackjson Serializer
 *
 * @author shidong
 * @since JDK 1.8
 */
public class OAuth2ExceptionnSerializer extends StdSerializer<OAuth2Exception> {

    public OAuth2ExceptionnSerializer() {
        super(OAuth2Exception.class);
    }

    @Override
    public void serialize(OAuth2Exception value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        //MyBadCredentialsException exception = (MyBadCredentialsException)value;
        gen.writeStartObject();
        gen.writeBooleanField("isSuccess", Boolean.FALSE);
        gen.writeObjectField("message", value.getMessage());
        gen.writeObjectField("code", ResultCodeConstants.NEEDLOGIN);
        gen.writeObjectField("data", null);
        //被迫下线的异常
        if(value.getHttpErrorCode()==401){
            if (value.getOAuth2ErrorCode().equals(ResultCodeConstants.LOGOUT)){
                gen.writeObjectField("code",value.getOAuth2ErrorCode());
            }
        }else if (value.getHttpErrorCode()==403){
            gen.writeObjectField("code",value.getHttpErrorCode());
        }else {
            if (value instanceof MyBadCredentialsException){
                gen.writeObjectField("code",((MyBadCredentialsException)value).getCode());
            }
        }
        //gen.writeObjectField("code",);
        //		if (value.getAdditionalInformation() != null)
        //		{
        //			for (Map.Entry<String, String> entry : value.getAdditionalInformation().entrySet())
        //			{
        //				String key = entry.getKey();
        //				String add = entry.getValue();
        //				gen.writeStringField(key, add);
        //			}
        //		}
        gen.writeEndObject();

    }


}
